# online_answer_records/crud.py
from sqlalchemy.orm import Session
from typing import List, Optional
from . import models, schemas


class CRUDOnlineAnswerRecord:
    def get_by_id(self, db: Session, record_id: int) -> Optional[models.OnlineAnswerRecord]:
        return db.query(models.OnlineAnswerRecord).filter(models.OnlineAnswerRecord.id == record_id).first()

    def get_by_user(self, db: Session, user_id: int, skip: int = 0, limit: int = 100) -> List[models.OnlineAnswerRecord]:
        return db.query(models.OnlineAnswerRecord).filter(
            models.OnlineAnswerRecord.user_id == user_id
        ).offset(skip).limit(limit).all()

    def get_by_session(self, db: Session, session_id: str) -> List[models.OnlineAnswerRecord]:
        return db.query(models.OnlineAnswerRecord).filter(
            models.OnlineAnswerRecord.session_id == session_id
        ).all()

    def get_all(self, db: Session, skip: int = 0, limit: int = 100) -> List[models.OnlineAnswerRecord]:
        return db.query(models.OnlineAnswerRecord).offset(skip).limit(limit).all()

    def create(self, db: Session, record_in: schemas.OnlineAnswerRecordCreate) -> models.OnlineAnswerRecord:
        db_record = models.OnlineAnswerRecord(**record_in.dict())
        db.add(db_record)
        db.commit()
        db.refresh(db_record)
        return db_record

    def update(self, db: Session, record_id: int, record_in: schemas.OnlineAnswerRecordUpdate) -> Optional[models.OnlineAnswerRecord]:
        db_record = self.get_by_id(db, record_id)
        if db_record:
            update_data = record_in.dict(exclude_unset=True)
            for field, value in update_data.items():
                setattr(db_record, field, value)
            db.commit()
            db.refresh(db_record)
            return db_record

    def delete(self, db: Session, record_id: int) -> bool:
        db_record = self.get_by_id(db, record_id)
        if db_record:
            db.delete(db_record)
            db.commit()
            return True
        return False


crud_online_answer_record = CRUDOnlineAnswerRecord()